﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Windows.Forms;
using PPIMobileInterface;
using PPIMobileInterface.Entities;
using PPIMobileInterface.Logic;
using PPIDesktopClient.Logic;
using PPIDesktopClient.General;
using PPIDesktopClient.Entities;
namespace PPIDesktopClient
{
    public partial class frmCopyMobile : frmDialogBase
    {
        private string m_NewSDFPath="";
        public string GetSDFPath() {
            return m_NewSDFPath;
        }
        public frmCopyMobile()
        {
            InitializeComponent();
        }
        private void btnBrowse_Click(object sender, EventArgs e)
        {
            try
            {
                bool _RootSDF = false;
                string[] _TempList;
                string _DirName;
                string _DBName;
                DateTime _TempDate;
                if (fbrDialog.ShowDialog() == DialogResult.OK)
                {
                    lstDBList.Items.Clear();
                    foreach (string _Entry in Directory.GetFileSystemEntries(fbrDialog.SelectedPath))
                    {
                        if (Directory.Exists(_Entry))
                        {
                            _TempList = _Entry.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                            _DirName = _TempList[_TempList.Length - 1];
                            _TempList = Directory.GetFiles(_Entry, "*.sdf", SearchOption.TopDirectoryOnly);
                            if (_TempList.Length == 1)
                            {
                                _DBName = _TempList[0];
                                if (Utils.TestDatabase(_DBName))
                                {
                                    if (DateTime.TryParseExact(_DirName, "yyyyMMddHHmmss", null, System.Globalization.DateTimeStyles.None, out _TempDate) || DateTime.TryParseExact(_DirName, "yyyyMMdd", null, System.Globalization.DateTimeStyles.None, out _TempDate))
                                        lstDBList.Items.Add(new ListBoxItem(_TempDate.ToString("MM/dd/yyyy HH:mm:ss"), _DBName));
                                    else
                                        lstDBList.Items.Add(new ListBoxItem(_DirName, _DBName));
                                }
                                else
                                    lstDBList.Items.Add(new ListBoxItem("(Invalid)" + _DirName, ""));
                            }
                            else if (_TempList.Length > 1)
                                lstDBList.Items.Add(new ListBoxItem("(Multiple)" + _DirName, ""));
                            else if (_DirName != "Images")
                                lstDBList.Items.Add(new ListBoxItem("(No DB)" + _DirName, ""));
                        }
                        else if (_Entry.Substring(_Entry.Length - 4) == ".sdf")
                        {
                            _TempList = _Entry.Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries);
                            if (_RootSDF)
                                lstDBList.Items.Add(new ListBoxItem("(Multiple)ROOT\\" + _TempList[_TempList.Length - 1], ""));
                            else if (!Utils.TestDatabase(_Entry))
                                lstDBList.Items.Add(new ListBoxItem("(Invalid)ROOT\\" + _TempList[_TempList.Length - 1], ""));
                            else
                            {
                                lstDBList.Items.Add(new ListBoxItem("ROOT\\" + _TempList[_TempList.Length - 1], _Entry));
                                _RootSDF = true;
                            }
                        }
                    }
                    btnSync.Enabled = lstDBList.Items.Count > 0;
                }
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmCopyMobile.btnBrowse_Click()", ex.Source, ex.Message, ex.StackTrace);
            }
        }
        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        private void btnSync_Click(object sender, EventArgs e)
        {
            try
            {
                string _Failed = "";
                string _FileName;
                string _NewFolderName;
                Random random = new Random();
                foreach (ListBoxItem _item in lstDBList.Items)
                {
                    if (_item.Value != "")
                    {
                        try
                        {
                            string SelectedPath;
                            SelectedPath = Path.GetDirectoryName(_item.Value);
                            if (DirHelper.isDirectory(Constants.K_InboxPath))
                            {

                                DirectoryInfo tmpSource = new DirectoryInfo(SelectedPath);
                                _NewFolderName = SelectedPath.Substring(SelectedPath.LastIndexOf("\\") + 1) + "_" + random.Next(int.MinValue, int.MaxValue).ToString();
                                DirectoryInfo tmpDestination = new DirectoryInfo(Constants.K_OutboxPath + "\\" + _NewFolderName);
                                DirHelper.CopyFiles(tmpSource, tmpDestination, true);
                                _FileName = _item.Value.Substring(_item.Value.LastIndexOf("\\") + 1);
                                m_NewSDFPath = Constants.K_OutboxPath + _NewFolderName + "\\" + _FileName;
                                Utils.AddAuditableColumns(m_NewSDFPath);
                                Utils.AddProjectColumn(m_NewSDFPath);
                                Deploy _Deploy = new Deploy(m_NewSDFPath);
                                _Deploy.StartDeploy();
                                LVendor_Project.InsertProjects(m_NewSDFPath);
                            }
                        }
                        catch
                        {
                            _Failed += "\n" + fbrDialog.SelectedPath + _item.Value;
                        }
                    }
                }
                if (_Failed != "")
                    MessageBox.Show("The following mobile databases failed to be copied:\n" + _Failed);
                else
                {
                    MessageBox.Show("Mobile database copied.");
                    this.Close();
                }


                btnSync.Enabled = false;
            }
            catch (Exception ex)
            {
                ErrorManager.Log("frmCopyMobile.btnSync_Click()", ex.Source, ex.Message, ex.StackTrace);
            }
        }
        private void frmCopyMobile_Resize(object sender, EventArgs e)
        {
        }
    }
}
